package fun.yyds.common.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author:joker
 * @Date:2022/3/12
 * @version:1.0
 */
@Data
@Slf4j
public class ExcelCommonLisenter<T extends ExcelBaseAo> extends AnalysisEventListener<T> {

    /**
     * 解析出的数据
     */
    List<T> list = Lists.newArrayList();

    /**
     * 起始数据行
     */
    private Integer headRowNumber;

    /**
     * 合并单元格
     */
    private List<CellExtra> extraMergeInfoList = Lists.newArrayList();

    public ExcelCommonLisenter(Integer headRowNumber) {
        this.headRowNumber = headRowNumber;
    }

    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
        switch (extra.getType()) {
            case COMMENT:
            case HYPERLINK: {
//                if ("Sheet1!A1".equals(extra.getText())) {
//                    log.info("额外信息是超链接,在rowIndex:{},columnIndex;{},内容是:{}", extra.getRowIndex(),
//                            extra.getColumnIndex(), extra.getText());
//                } else if ("Sheet2!A1".equals(extra.getText())) {
//                    log.info(
//                            "额外信息是超链接,而且覆盖了一个区间,在firstRowIndex:{},firstColumnIndex;{},lastRowIndex:{},lastColumnIndex:{},"
//                                    + "内容是:{}",
//                            extra.getFirstRowIndex(), extra.getFirstColumnIndex(), extra.getLastRowIndex(),
//                            extra.getLastColumnIndex(), extra.getText());
//                } else {
//                    log.error("Unknown hyperlink!");
//                }
                break;
            }
            case MERGE: {
//                log.info(
//                        "额外信息是合并单元格,而且覆盖了一个区间,在firstRowIndex:{},firstColumnIndex;{},lastRowIndex:{},lastColumnIndex:{}",
//                        extra.getFirstRowIndex(), extra.getFirstColumnIndex(), extra.getLastRowIndex(),
//                        extra.getLastColumnIndex());
                if (extra.getRowIndex() >= headRowNumber) {
                    extraMergeInfoList.add(extra);
                }
                break;
            }
            default: {
            }
        }
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        ReadRowHolder readRowHolder = analysisContext.readRowHolder();
        Integer rowIndex = readRowHolder.getRowIndex();
        t.setLineNo(rowIndex + 1);
        list.add(t);

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    }

    public List<CellExtra> getExtraMergeInfoList() {
        return extraMergeInfoList;
    }

    public List<T> getData() {
        return list;
    }


}
